﻿using System;
using System.Windows;
using System.Windows.Media;

namespace Leow.SelectableCanvas
{
    public class HatchedBorderThumb : RectangleThumb
    {
        private Pen _hatchingPen;

        public HatchedBorderThumb()
        {
            Loaded += LoadedEventHandler;
        }

        private void LoadedEventHandler(object sender, RoutedEventArgs e)
        {
            Loaded -= LoadedEventHandler;

            _hatchingPen = new Pen(BorderBrush, 1);

            Background = null;
            BorderBrush = null;

            InvalidateVisual();
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            var outerRect = new Rect(0, 0, ActualWidth, ActualHeight);
            var innerRect = new Rect(
                BorderThickness.Left,
                BorderThickness.Top,
                ActualWidth - BorderThickness.Left - BorderThickness.Right,
                ActualHeight - BorderThickness.Top - BorderThickness.Bottom);

            var geometry = new CombinedGeometry(
                GeometryCombineMode.Exclude,
                new RectangleGeometry(outerRect),
                new RectangleGeometry(innerRect));
            drawingContext.PushClip(geometry);

            drawingContext.DrawRectangle(Brushes.Transparent, null, outerRect);

            double limit = 2 * Math.Max(ActualWidth, ActualHeight);
            for (double n = 0; n < limit; n += 5)
            {
                drawingContext.DrawLine(_hatchingPen, new Point(0, n), new Point(n, 0));
            }
        }
    }
}
